package lib

import (
	"github.com/go-ini/ini"
	"go.uber.org/zap"
	"time"
)

type App struct {
	UserName        string
	UseMultipoint   bool
	RuntimeRootPath string
	PrefixUrl       string
	Location        string
}

var AppSetting = &App{}

type Server struct {
	RunMode      string
	Address      string
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

var ServerSetting = &Server{}

type Mysql struct {
	Host         string
	Name         string
	UserName     string
	Password     string
	MaxIdleConns int
	MaxOpenConns int
	LogZap       bool
}

var MysqlSetting = &Mysql{}

type Redis struct {
	Addr     string
	Password string
	DB       int
}

var RedisSetting = &Redis{}

type Log struct {
	Level      string
	Filename   string
	MaxSize    int
	MaxAge     int
	MaxBackups int
}

var LogSetting = &Log{}

type SmsCode struct {
	AccessKeyId     string
	AccessKeySecret string
	SignName        string
	TemplateCode    string
	CodeLength      int
}

var SmsCodeSetting = &SmsCode{}

type JWT struct {
	SigningKey  string
	ExpiresTime time.Duration
	BufferTime  int64
	Issuer      string
}

var JWTSetting = &JWT{}

type Images struct {
	ImagePath    string
	ImageMaxSize int64
}

var ImagesSetting = &Images{}

type Oss struct {
	EndPoint   string
	BucketName string
	BasePath   string
	BucketUrl  string
}

var OssSetting = &Oss{}

// InitConfig Init 读取配置文件信息
func InitConfig() {
	cfg, err := ini.Load("./conf/setting.ini")
	if err != nil {
		zap.L().Fatal("Fail to parse 'conf/app.ini'")
		return
	}
	if err = cfg.Section("app").MapTo(AppSetting); err != nil {
		zap.L().Fatal("Fail to section 'app'")
		return
	}

	if err = cfg.Section("server").MapTo(ServerSetting); err != nil {
		zap.L().Fatal("Fail to section 'server'")
		return
	}
	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	if err = cfg.Section("mysql").MapTo(MysqlSetting); err != nil {
		zap.L().Fatal("Fail to section 'mysql'")
		return
	}

	if err = cfg.Section("redis").MapTo(RedisSetting); err != nil {
		zap.L().Fatal("Fail setting 'redis'")
		return
	}
	if err = cfg.Section("log").MapTo(LogSetting); err != nil {
		zap.L().Fatal("Fail setting 'log'")
		return
	}

	if err = cfg.Section("sms_code").MapTo(SmsCodeSetting); err != nil {
		zap.L().Fatal("Fail setting 'sms_code'")
		return
	}

	if err = cfg.Section("jwt").MapTo(JWTSetting); err != nil {
		zap.L().Fatal("Fail to section 'jwt'")
		return
	}
	if err = cfg.Section("images").MapTo(ImagesSetting); err != nil {
		zap.L().Fatal("Fail setting 'images'")
		return
	}
	if err = cfg.Section("oss").MapTo(OssSetting); err != nil {
		zap.L().Fatal("Fail setting 'oss'")
		return
	}
}
